package com.sskj.base.api;

import com.sskj.base.base.App;
import com.sskj.base.utils.SPUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RetrofitFactory {
    public static Retrofit retrofit;

    private RetrofitFactory() {
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.SERVER_ADDRESS)
                .addConverterFactory(GsonConvertFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(initClient())
                .build();
    }

    private OkHttpClient initClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(initHeaderInterceptor())
                .addInterceptor(initLogInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private Interceptor initLogInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;

    }

    private Interceptor initHeaderInterceptor() {
        Interceptor headerInterceptor = chain -> {
            Request request = chain.request();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("app", "app");
                for (int i = 0; i < body.size(); i++) {
                    builder.add(body.name(i), body.value(i));
                }
                request.newBuilder()
                        .header("Content-Type", "application/json")
                        .header("token", (String) SPUtils.get(App.INSTANCE, "token", ""))
                        .post(builder.build())
                        .build();
            }
            return chain.proceed(request);
        };
        return headerInterceptor;
    }


    public static RetrofitFactory instance;


    public static <T> T create(Class<T> service) {
        if (instance == null) {
            instance = new RetrofitFactory();
        }
        return retrofit.create(service);
    }
}
